<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

// 使用类

use App\Http\Controllers\Controller;

// 商品页控制器
class GoodsController extends Controller
{
    // 商品页

    public function index($id){

    	// 设置cookie
    	// 获取商品相关数据
    	$goods=\DB::table("goods")
                    ->select("goods.*","goodsdetails.*")
                    ->join("goodsdetails","goodsdetails.gid","=","goods.id")
                    ->where("goods.id",$id)
                    ->first();
            
    	// 商品图片表

    	$goodsImg=\DB::table("goodsimg")->where("gid",$id)->get();

    	// 查询商品对应品论

    	$commentTot=\DB::table("comment")->where("gid",$id)->count();

        //好评数
    	$goodTot=\DB::table("comment")
                    ->where('gid','=',$id)
                    ->where("start",">",4)
                    ->count();

        //差评数 
    	$chaTot=\DB::table("comment")
                    ->where('gid','=',$id)
                    ->where("start","<=",2)
                    ->count();
        //中评
    	$zhongTot=$commentTot-$goodTot-$chaTot;

    	$arr=array(
    		"commentTot"=>$commentTot,
    		"goodTot"=>$goodTot,
    		"chaTot"=>$chaTot,
    		"zhongTot"=>$zhongTot,

    		);


        //评价
    	$comment=\DB::table("comment")->where("gid",$id)->get();


        //热销
        $hotgoods =\DB::table('orders')
                     ->select(\DB::raw('goods.*,orders.gid,COUNT(orders.gid) AS counts'))
                     ->leftJoin('goods', 'goods.id', '=', 'orders.gid')
                     ->groupBy('orders.gid')
                     ->orderBy('counts', 'desc')
                     ->limit(5)
                     ->get();


    	// 格式化数据

    	$data=array(

    		"goods"=>$goods,
    		"goodsImg"=>$goodsImg,
    		"arr"=>$arr,
            "comment"=>$comment,
    		"hotgoods"=>$hotgoods,
    		);

    	// 加载页面
// dd($hotgoods);
    	return view("home.goods")->with($data);
    }
}
